﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using 安检系统.Model;
using 安检系统.Utils;
using 安检系统.ViewModel;

namespace 安检系统
{
    /// <summary>
    /// DispatchRecord.xaml 的交互逻辑
    /// </summary>
    public partial class DispatchRecord : Window
    {
        DispatchRecordModel viewModel;
        SynchronizationContext _syncContext = null;
        public String carNo = "";
        public String carEffluentStandard = "";
        public DispatchRecord()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;

            viewModel = new DispatchRecordModel();
            this.DataContext = viewModel;
            this.Loaded += Windows_Load;
        }

        private void Windows_Load(object sender, RoutedEventArgs e)
        {
            this.loadData();
        }

        private void loadData()
        {
            new Task(() =>
            {
                try
                {
                    JObject paramJSON = new JObject();                    
                    paramJSON.Add("type", "2");
                    String ip = App.GetBaseInfo().HttpServerIp;
                    String port = App.GetBaseInfo().HttpServerPort;

                    String response = HttpPostHelper.doHttpPost("http://" + ip + ":" + port + "/ytBillLineUp/queryList", paramJSON.ToString());
                    JObject respJson = JObject.Parse(response);
                    bool success = (bool)respJson["success"];
                    if (success)
                    {
                        var jsonStr = respJson["data"].ToString();
                        List<Car> records = JsonConvert.DeserializeObject<List<Car>>(jsonStr);
                        _syncContext.Post(SetDataList, records);
                    }
                }
                catch (Exception ex) { }
            }).Start();
        }

        private void SetDataList(object obj) 
        {
            viewModel.items.Clear();
            if (null == obj) return;
            List<Car> records = (List<Car>)obj;

            foreach (Car record in records)
            {
                viewModel.items.Add(record);
            }
        }
    }
}
